package com.xiyue.leaspring.config;

import javax.jms.Destination;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;

@Configuration
//一下等价于<context:property-placeholder location="classpath:dev/config/*.properties"/>
@PropertySource("classpath:dev/config/activemq.properties")
public class MessageProviderConfig {
	@Value("${activemq.broker.url}")
	private String brokerURL;
	@Value("${activemq.topic.name}")
	private String topicName;
	@Value("${activemq.user.name}")
	private String username;
	@Value("${activemq.user.password}")
	private String password;
	
	@Bean(name="jmsTemplate")
	public JmsTemplate getJmsTemplate(SingleConnectionFactory connectionFactory) {
		JmsTemplate jmsTemplate = new JmsTemplate();
		jmsTemplate.setConnectionFactory(connectionFactory);
		return jmsTemplate;
	}
	
	@Bean(name="destination")
	public Destination createDestination() {
		ActiveMQTopic amq = new ActiveMQTopic(this.topicName);
		return amq;
	}
	
	@Bean(name="connectionFactory")
	public SingleConnectionFactory createConnectionFactory(ActiveMQConnectionFactory targetActiveMQConnectionFactory) {
		SingleConnectionFactory scf = new SingleConnectionFactory();
		scf.setTargetConnectionFactory(targetActiveMQConnectionFactory);
		return scf;
	}
	
	@Bean(name="targetConnectionFactory")
	public ActiveMQConnectionFactory createTargetConnectionFactory() {
		ActiveMQConnectionFactory acf = new ActiveMQConnectionFactory();
		acf.setBrokerURL(this.brokerURL);
		acf.setUserName(this.username);
		acf.setPassword(this.password);
		return acf;
	}
}
